//
//  RYCollectionViewHandle.swift
//  App_Profile
//
//  Created by 蒋晨成 on 2022/2/9.
//

import Adaptor
import Foundation
import UIKit

public final class RYCollectionHandler: NSObject {
    public var dataSource: [[RYBaseCellModel]]?
}

extension RYCollectionHandler: UICollectionViewDataSource {
    public func numberOfSections(in _: UICollectionView) -> Int {
        dataSource?.count ?? 0
    }

    public func collectionView(_: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        dataSource?[safe: section]?.count ?? 0
    }

    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cellViewModel = dataSource?[safe: indexPath.section]?[safe: indexPath.row] else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UICollectionViewCell", for: indexPath)
            cell.backgroundColor = .blue
            return cell
        }

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellViewModel.identifier, for: indexPath)
        if let baseCell = cell as? RYBaseCell {
            baseCell.reusableCell(cellViewModel)
            cellViewModel.indexPath = indexPath
        }
        return cell
    }
}

extension RYCollectionHandler: UICollectionViewDelegate {
    public func collectionView(_: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let cellViewModel = dataSource?[safe: indexPath.section]?[safe: indexPath.row] else { return }
        cellViewModel.action?(cellViewModel)
    }
}

extension RYCollectionHandler: UICollectionViewDelegateFlowLayout {
    public func collectionView(_: UICollectionView, layout _: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        guard let cellViewModel = dataSource?[safe: indexPath.section]?[safe: indexPath.row] else {
            return .zero
        }
        return CGSize(width: Adaptor.Screen.width, height: cellViewModel.cellHeight)
    }
}
